#!/usr/bin/env python
# -*- coding: utf-8 -*-

# hexarea.py

# Copyright 2009 Diego Hansen Hahn (aka DiegoHH) <diegohh90 [at] hotmail [dot] com>

# lazynds is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License.

# lazynds is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with lazynds. If not, see <http://www.gnu.org/licenses/>.

''' Work-in-Progress '''
# Será melhorado em versões posteriores

#import time
import array
import os
import binascii
from math import ceil

import gtk
import pango

#import PyTable

#zelda = os.path.join(os.path.realpath(os.path.dirname(__file__)), 'zeldao.tbl')
#try:
#	table = PyTable.PyTable(zelda,"1252")
#except:
#	table = None
table = None

__author__ = "Diego Hansen Hahn"
__version__ = "v2.0"

# Manipuladores de caracteres

if not table:
	encoding = "ascii"
	def ascii(x):
		'''
		Retorna o carectere correspondente da tabela ASCII
		'''
		if x < " " or x > "~":
			return '.'
		else:
			return x
else:
	encoding = table.encoding
	def ascii(x):
		return table.get(x,".")
# ---------------------------------------------------------------------------------------------------------

import threading

class WriteThread(threading.Thread):
	'''
	Teste colocando a escrita em threads
	'''
	def __init__(self, textview, buffer, mode = None):
		threading.Thread.__init__(self)

		self.textview = textview
		self.textbuffer= self.textview.get_buffer()
		self.buffer = buffer

	def run(self):
		self.textbuffer.set_text(self.buffer.decode(encoding))
		self.textview.set_sensitive(True)


class Texts(gtk.TextView):
	def __init__(self, width, height):
		gtk.TextView.__init__(self)
		self.textbuffer = self.get_buffer()

		self.modify_font(pango.FontDescription('monospace 12'))
		self.set_editable(False)
		self.set_size_request(width, height)

	def Draw(self, buffer):
		self.set_sensitive(False)
		wThread = WriteThread(self, buffer)
		wThread.start()

class HexArea(gtk.ScrolledWindow):
	'''
	Há uma maneira melhor de fazer isso??
	'''
	def __init__(self):
		gtk.ScrolledWindow.__init__(self)
		self.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
		self.hexText = Texts(490, -1)
		self.hexText.set_indent(5)
		self.asciiText = Texts(-1, -1)

		self.asciitext = str()
		self.hextext = str()

	def Make_Area(self):
		box = gtk.HBox()
		box.pack_start(self.hexText, False, False)
		box.pack_start(self.asciiText, True, True)
		self.add_with_viewport(box)

	def Draw(self, buffer):
		# Se o buffer for False, retorna nada
		if not buffer:
			return

		hextext = str()
		asciitext = str()

		while gtk.events_pending():
			gtk.main_iteration()

		#iter = enumerate(buffer)
		for x in range(len(buffer)):#iter:
			char = buffer[x]
			hextext += binascii.b2a_hex(char).upper() + ' '
			asciitext += ascii(char)
			if (x + 1) % 16 is 0:
				asciitext += os.linesep
				hextext += os.linesep

		self.hexText.Draw(hextext)
		self.asciiText.Draw(asciitext)

		self.RestartAdjustment()

	def RestartAdjustment(self):
		adj = self.get_vadjustment()
		adj.props.value = 0
		self.set_vadjustment(adj)
